/**
 * 解析url参数, 举例：
 * 		?a=1&b=2	=>	{a: 1, b: 2}
 * 		?a=1&a=2	=>	{a: [1, 2]}
 * 		?a[1]=1&a[2]=2	=> {a: [, 1, 2]}
 * 		?a[a]=1&a[b]=2	=> {a: {a: 1, b: 2}}
 * 		?a[a]=1&a[a]=2	=> {a: {a: [1, 2]}}
 * 
 * @param {String} urlOrScene url
 * @returns params object
 */
export function parseParam(urlOrScene) {
	if (!urlOrScene) {
		return {};
	}

	if ('string' !== typeof(urlOrScene)) {
		console.warn("unsupported parameter type: ", typeof(urlOrScene));
		return {};
	}

	return urlOrScene.slice(urlOrScene.indexOf("?") + 1).split("&").reduce((prev, curr) => {
		let [key, val] = curr.split("=");

		if (!val) return prev;

		//  解析 'a[name]' -> [a, name]
		let path = key.split(/[\[\]]/g).filter(x => x);

		deepParseParam(
			prev, // {}
			path, // [a, name]
			val // tiger
		);

		return prev;
	}, {});
}

export function deepParseParam(obj, path, val) {
	let i = 0;
	let key = path[0];

	for (; i < path.length - 1; i++) {
		if (!obj[key]) {
			if (path[i + 1].match(/^\d+$/)) {
				obj[key] = [];
			} else {
				obj[key] = {};
			}
		}
		obj = obj[key];
		key = path[++i];
	}

	// decodeURIComponent解码
	let value = val;

	try {
		value = decodeURIComponent(val);
	} catch (error) {
	}


	if (obj[key]) {
		if (Array.isArray(obj[key])) {
			obj[key].push(value);
		} else if ("object" === typeof(obj[key])) {
			obj[key] = value;
		} else {
			obj[key] = [obj[key], value];
		}
	} else {
		obj[key] = value;
	}
}


